package cn.dust.design.pattern.creational.singleton;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @Author: dust
 * @Date: 2019/11/25 18:55
 */
public class LazySingleton {

    private static LazySingleton lazySingleton=null;
    //模拟反射攻击
    private static boolean flag=true;

    private LazySingleton(){
        if(flag){
            flag=false;
        }else{
            throw new RuntimeException("单例构造器禁止反射调用");
        }
    }

    public synchronized static LazySingleton getInstance(){
        if(lazySingleton==null){
           lazySingleton= new LazySingleton();
        }
        return lazySingleton;
    }

//    public static void main(String[] args) {
//        Class objectClass=LazySingleton.class;
//        try {
//            Constructor constructor=objectClass.getDeclaredConstructor();
//            constructor.setAccessible(true);
//
//            LazySingleton o1=LazySingleton.getInstance();
//            Field flag=o1.getClass().getDeclaredField("flag");
//            flag.setAccessible(true);
//            flag.set(o1,true);
//
//            LazySingleton o2= (LazySingleton) constructor.newInstance();
//            System.out.println(o1);
//            System.out.println(o2);
//            System.out.println(o1==o2);
//        } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchFieldException e) {
//            e.printStackTrace();
//        }
//    }

}
